<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="67px">
        <SearchFormGroup
          :data="searchParam"
          @change-search="handleSearchChange"
          @change-gage-equip-code="changeEquipCode"
        />
        <el-form-item label="监控类别">
          <el-select
            v-model="searchParam.abilityType"
            placeholder="请选择监控类别"
            clearable
          >
            <el-option
              v-for="item in useDictionary('AbilityTypeMin')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="特性名称">
          <el-select
            v-model="searchParam.specificId"
            placeholder="请选择特性名称"
            clearable
            filterable
            :filter-method="customFilter5"
            :disabled="!canSelectSpecific"
            :loading="specificLoading"
            loading-text="加载中..."
            @change="specificChange"
          >
            <el-option
              v-for="item in filteredOptions5"
              :key="item.id"
              :label="item.paramName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮件时间">
          <el-date-picker
            v-model="searchParam.sendTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getsendTime"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetHandle">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        :maxHeight="tableHeight"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="工段"
          prop="workshopSectionCode"
          min-width="90"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="工序"
          prop="processCode"
          min-width="80"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="生产线"
          prop="processEquipCode"
          min-width="80"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="型号描述"
          prop="modelName"
          min-width="110"
          show-overflow-tooltip
          align="left"
        >
        </el-table-column>
        <el-table-column
          label="产品型号"
          prop="modelCode"
          min-width="90"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="检具名称"
          prop="gageEquipMarkCode"
          min-width="90"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="特性名称"
          prop="parameterDesc"
          min-width="150"
          show-overflow-tooltip
          align="left"
        >
        </el-table-column>
        <el-table-column
          label="邮件时间"
          prop="sendTime"
          min-width="150"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="生成工单"
          prop="orderId"
          min-width="75"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ $index, row }">
            <span>{{ row.orderId ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="55" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
              >
                <i-ep-search />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <pcmnoticerecord-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDownload,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import { authAllPerm } from "@/utils";
import _ from "lodash-es";
import { useDictStoreHook } from "@/store/modules/dictionary";
import {
  getMdmprocessListApi,
  getMdmproductinfosApi1,
  getSpecificListApi,
} from "@/utils/commonData";
import { deepClone } from "@/utils/commonHooks";
import SearchFormGroup from "@/views/pcm/pcmMonitoring/components/SearchFormGroup1.vue";

const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "PCMPCMNOTICERECORD",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/dmpDosPcm/psmmailsendrecord/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  //   workshopSectionId: "",
  //   processId: "",
  //   processEquipId: "",
  //   modelId: "",
  //   gageEquipMarkId: "",
  //   programName: "",
  //   processDataType: "",
  //   parameterId: "",
  // 工段
  workshopSectionId: "",
  workshopSectionCode: "",
  // 项目
  // projectCode: "",
  // projectId: "",
  // 工序
  processCode: "",
  processId: "",
  // 设备
  equipCode: "",
  equipId: "",
  // 产品型号
  productCode: "",
  productName: "",
  productId: "",
  // 检具类型
  gageEquipToolKind: "",
  // 检具名称
  gageEquipCode: "",
  // 机器号
  gageEquipMarkCode: "",
  // 特性
  specificCode: "",
  specificId: "",
  specificName: "",
  sendTimeSearch: [],
  sendTimeStart: "",
  sendTimeEnd: "",
  // 1 工艺   2 过程
  type: 2,

  // 监控类别
  abilityType: "",
};

const deleteParam = {
  api: "/dmpDosPcm/psmmailsendrecord/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

onMounted(() => {
  searchParam.value.type = 2;
  getTableList();
});

// 处理传回数据
const handleSearchChange = (data) => {
  Object.assign(searchParam.value, data);
  // 可执行字段相关的特定逻辑
  searchParam.value.modelId = searchParam.value.productId;
  searchParam.value.parameterId = searchParam.value.specificId;
};
// 特性值变化
function specificChange(id: string) {
  if (id) {
    const current: any =
      specificList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.specificCode = current.paramCode || "";
    searchParam.value.specificName = current.paramName || "";
  } else {
    searchParam.value.specificCode = "";
    searchParam.value.specificName = "";
  }
}
// 间距变化
const changeEquipCode = (id: string) => {
  if (id) {
    searchParam.value.specificCode = "";
    searchParam.value.specificName = "";
    searchParam.value.specificId = "";
  }
};
// 获取特性值列表
const specificList = ref<any>([]);
const specificLoading = ref(false);

async function getSpecificList() {
  specificLoading.value = true;
  specificList.value =
    (await getSpecificListApi({
      equipId: searchParam.value.equipId,
      gageEquipMarkCode: searchParam.value.gageEquipCode,
      modelId: searchParam.value.productId,
      processId: searchParam.value.processId,
    }).finally(() => {
      specificLoading.value = false;
    })) || [];

  filteredOptions5.value = deepClone(specificList.value);
}

const filteredOptions5 = ref([]);
// 使用 debounce 包装过滤方法
const customFilter5 = _.debounce((query) => {
  if (!query) {
    filteredOptions5.value = [...specificList.value];
    return;
  }
  filteredOptions5.value = specificList.value.filter((option: any) =>
    option.paramName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

// 检测必填项，筛选特性值列表
const canSelectSpecific = ref(false);
watch(
  () => searchParam.value,
  (newVal) => {
    const arr = deepClone(newVal);
    // console.log("特性值newVal", arr);
    if (
      newVal.equipCode &&
      newVal.gageEquipCode &&
      newVal.productCode &&
      newVal.processCode
    ) {
      canSelectSpecific.value = true;
      getSpecificList();
    } else {
      // specificList.value = [];
      searchParam.value.specificId = "";
      searchParam.value.specificCode = "";
      searchParam.value.specificName = "";
      canSelectSpecific.value = false;
      specificList.value = [];
      filteredOptions5.value = [];
    }
  },
  {
    deep: true,
  }
);

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/psmmailsendrecord/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开邮件发送记录表表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改邮件发送记录表";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增邮件发送记录表";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开邮件发送记录表表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "邮件发送记录表详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getsendTime(data: any) {
  if (data) {
    searchParam.value.sendTimeStart = data[0];
    searchParam.value.sendTimeEnd = data[1];
  } else {
    searchParam.value.sendTimeStart = "";
    searchParam.value.sendTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/dmpDosPcm/psmmailsendrecord/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

const resetHandle = () => {
  reset();
};
</script>
